package com.etmvc.tools;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.etmvc.core.AuthName;
import com.etmvc.core.ManageController;

public class AuthUtils {
	private static Map<String, List<String>> allUrls = null;
	public static Map<String, List<String>> getMenuUrls(String authBasePath){
		return getUrls(authBasePath, true);
	}
	public static Map<String, List<String>> getAllUrls(String authBasePath){
		return getUrls(authBasePath, false);
	}
	public static Map<String, List<String>> getUrls(String authBasePath,boolean onlyMenu){
//		if (allUrls != null) {
//			return allUrls;
//		}
//		System.out.println("allUrls has no data,loading....");
		allUrls = new HashMap<String, List<String>>();
		try {
			List<Class> controllers = ClassUtils.getClasses(authBasePath);
			for (Class class2 : controllers) {
				if (class2.getSuperclass() != ManageController.class) {
					continue;//不是后台受控的controller，跳过
				}
				String controllerName = "无";
				AuthName controllerNameAnnotation = (AuthName) class2.getAnnotation(AuthName.class);
				if (controllerNameAnnotation != null) {
					controllerName = controllerNameAnnotation.value();
				}
				Method[] methods = class2.getDeclaredMethods();
				List<String> actions = new ArrayList<String>();
				for (Method method : methods) {
					String actionName = "无";
					AuthName actionNameAnnotation = method.getAnnotation(AuthName.class);
					if (onlyMenu && (actionNameAnnotation==null || !actionNameAnnotation.menu())) {
						continue;
					}
					if (actionNameAnnotation != null) {
						actionName = actionNameAnnotation.value()+(actionNameAnnotation.menu()?"#menu":"");
					}
					actions.add(method.getName()+"#"+actionName);
				}
				String packageName = class2.getPackage().getName();
				String simpleClassName = class2.getSimpleName();
				String urlName = packageName.replaceFirst(authBasePath, "").replaceAll("\\.", "/")
					+"/"+simpleClassName.substring(0,1).toLowerCase()+simpleClassName.substring(1,simpleClassName.lastIndexOf("Controller"));
				allUrls.put(urlName+"#"+controllerName, actions);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return allUrls;
	}
}
